/*v9SsMbU6/en1uSuPJ2mptqF+jolE0EBwO372IvrfdFi2wKSOmX+ORnrDDvO5/aGv*/
/*
 * @Author: llixxm
 * @Date: 2022-03-29 16:29:51
 * @Description: 绘制辅助核算单元格
 */
import { toast, base } from 'nc-lightapp-front';

import { SelectItem } from '../../../public/components/FormItems';
import ReferLoader from '../../../public/ReferLoader';
import ReferWraper from '../../../public/components/ReferWraper'
const { NCFormControl, NCDatePicker, NCNumber, NCInput, NCSelect, NCInputNumber, NCHotKeys } = base;
const NCOption = NCSelect.NCOption;
const FORMAT = 'YYYY-MM-DD'; 
const TIMEFORMAT = 'YYYY-MM-DD HH:mm:ss';

function drawAssidCell(params) {
    let { record } = params;
    let { refpath, classid, defaultReferValue } = getRecordParams(record);
    if (refpath) {
        return drawReferLoader({ ...params, refpath, classid, defaultReferValue });
    } else if(record.selectCell && record.selectCell.attr){
        //打开弹框 ---辅助属性余额表
        return drawDefReferWraper({ ...params, refpath, classid, defaultReferValue })
    } else {
        return drawOtherAssid({ ...params, refpath, classid, defaultReferValue });
    }
}

function getRecordParams(record) {
    let refpath = record.selectCell && record.selectCell.refpath || record.refpath || record.refnodename || '';
    let classid = record.selectCell && record.selectCell.classid || record.classid || '';
    let defaultReferValue = record.selectCells || record.selectObj || record.selectRefer;
    return { refpath, classid, defaultReferValue };
}

//获取参照过滤需要的参数
function getReferParams(page) {
    let { json, accountingbook, buSecond, unitValueParam, isversiondate, versiondate, busiDate } = page.state;
    let pk_accountingbook = '', pk_accountingbooks = '', pk_org = '', pk_orgs = '';
    let dateStr = isversiondate ? versiondate : busiDate;
    if (Array.isArray(accountingbook)) {
        pk_accountingbook = accountingbook[0] && accountingbook[0].refpk || '';
        pk_accountingbooks = accountingbook.map(item => item.refpk).join(',');
    } else {
        pk_accountingbook = accountingbook.refpk;
        pk_accountingbooks = accountingbook.refpk
    }
    if (buSecond.length > 0) {
        pk_org = buSecond[0].refpk;
        pk_orgs = buSecond.map(item => item.refpk).join(',');
    } else {
        pk_org = unitValueParam;
        pk_orgs = '';
    }
    return { json, accountingbook, pk_accountingbook, pk_accountingbooks, pk_org, pk_orgs, dateStr };
}

//获取参照配置
function getReferConfig(params) {
    let { disabled, fieldid, refpath, classid, defaultReferValue, isMultiSelectedEnabled, isMultiSelectedUnit,
        pk_accountingbook, pk_accountingbooks, pk_org, pk_orgs, dateStr } = params; 
    let referUrl = refpath + ".js";
    let defaultConfig = {
        fieldid: fieldid,
        tag: referUrl,
        refcode: referUrl,
        value: defaultReferValue,
        isMultiSelectedEnabled: isMultiSelectedEnabled, //多选/单选
        disabled: disabled,
        isShowDisabledData: true,
        // unitProps: {
        //     refType: 'tree',
        //     refName: json['20023055-000014'], ///* 国际化处理： 业务单元*/
        //     refCode: 'uapbd.refer.org.BusinessUnitTreeRef',
        //     rootNode: { refname: json['20023055-000014'], refpk: 'root' }, ///* 国际化处理： 业务单元*/
        //     placeholder: json['20023055-000014'], ///* 国际化处理： 业务单元*/
        //     queryTreeUrl: '/nccloud/uapbd/org/BusinessUnitTreeRef.do',
        //     treeConfig: { name: [json['20023055-000015'], json['20023055-000016']], code: ['refcode', 'refname'] }, ///* 国际化处理： 编码,名称*/
        //     isMultiSelectedEnabled: false,
        //     //unitProps:unitConf,
        //     isShowUnit: false
        // },
        queryCondition: () => {
            return {
                "pk_accountingbook": pk_accountingbook,
                "pk_org": pk_org,
                "isDataPowerEnable": "Y",
                "DataPowerOperationCode": 'fi',
                dateStr: dateStr
            }
        },
        onChange: (val) => {
            onAssidReferChange({...params, val: val})
        }
    }
    if(isMultiSelectedUnit){
        //业务单元多选,辅助余额表 辅助明细账 支持
        defaultConfig.isShowUnit = true
        defaultConfig.unitValueIsNeeded = false
        defaultConfig.isShowDimission = true
        defaultConfig.unitCondition = {
            pk_accountingbook: pk_accountingbooks,
            pk_orgs: pk_orgs,
            'TreeRefActionExt': 'nccloud.web.gl.ref.OrgRelationFilterRefSqlBuilder'
        }
    } else {
        defaultConfig.unitCondition = {
            pk_org: pk_org,
            pk_financeorg: pk_org,
            'TreeRefActionExt':'nccloud.web.gl.ref.OrgRelationFilterRefSqlBuilder'
        }
    }
    
    return defaultConfig
}
function drawDefReferWraper(params) {
    let { page, record, fieldid } = params;
    let attrObj = record.selectCellAttr;
    let showArr = [];
    attrObj && attrObj.map((item) => {
        if (item) {
            item.itemKey = record.key;
        }
        if (item.select) {
            let showitem = "【" + item.name + ":";
            if (!item.selectName || item.selectName === '' || (Array.isArray(item.selectName) && item.selectName.length == 0)) { // 不选值，即为全选
                showitem += "ALL";
            } else if (item.enums) { // 枚举类型的，取枚举的name
                item.enums.map((enumcell, index) => {
                    if (enumcell.value === item.selectName) {
                        showitem += enumcell.name;
                    }
                })
            } else { // 参照的单选和多选
                if (Array.isArray(item.selectName)) {
                    showitem += item.selectName.join(',');
                } else {
                    showitem += item.selectName;
                }
            }
            showitem += "】";
            showArr.push(showitem);
        }
    })
    return (
        <ReferWraper
            // outStyle={{width: '200px', marginLeft: '10px'}}
            fieldid={fieldid}
            placeholder = {record.selectCell && record.selectCell.name}
            display={showArr.join('')}  //显示值
            onClick={() => page.setState({
                page: record.key
            },()=>{
                page.NewModal.show();
            })}
        />
    );
}

//渲染参照
function drawReferLoader(params) {
    let { page, classid, isMultiSelectedUnit } = params;
    let referParams = getReferParams(page);
    let { json, pk_accountingbook, pk_accountingbooks, pk_org, pk_orgs, dateStr } = referParams;
    let defaultConfig = getReferConfig({...params, ...referParams});
    let defaultUnitCondition = {
        pk_org: pk_org,
        pk_financeorg: pk_org,
        'TreeRefActionExt':'nccloud.web.gl.ref.OrgRelationFilterRefSqlBuilder'
    }
    let newOPtions = {}
    if (classid == 'b26fa3cb-4087-4027-a3b6-c83ab2a086a9' || classid == '40d39c26-a2b6-4f16-a018-45664cac1a1f') {//部门，人员
        newOPtions = {
            ...defaultConfig,
            isShowUnit: true,
            unitValueIsNeeded: false,
            isShowDimission: true,
            queryCondition: () => {
                return {
                    "pk_accountingbook": pk_accountingbook,
                    "pk_org": pk_org,
                    "isDataPowerEnable": "Y",
                    "DataPowerOperationCode": 'fi',
                    "dateStr": dateStr,
                    "busifuncode": "all",
                    isShowDimission: true
                }
            },
            unitCondition: isMultiSelectedUnit ? defaultConfig.unitCondition : defaultUnitCondition,
        }
    } else if (classid && classid.length === 20) {
        newOPtions = {
            ...defaultConfig,
            pk_defdoclist: classid,
        }
    } else {
        newOPtions = {
            ...defaultConfig,
        }
    }
    return (
        <div style={{ width: '100%' }}>
            <ReferLoader {...newOPtions} />
        </div>
    );
}
// 参照外的辅助
function drawOtherAssid(params) {
    let { classid } = params;
    switch (classid) {
        case 'BS000010000100001033': //日期
        case 'BS000010000100001034': //日期时间
            return drawNCDatePicker(params);
        case 'BS000010000100001032': //布尔
            return drawSelectItem(params);
        case 'BS000010000100001031': //数值(小数)
            return drawNCNumber(params);
        case 'BS000010000100001004': //整数
        case 'BS000010000100001001': //字符
            return drawNCFormControl(params);
        default:
            return <NCInput fieldid='checkvaluename' disabled />;
        // break;
    }
}
//日期
function drawNCDatePicker(params) {
    let { record, disabled, fieldid, attrcode, classid } = params;
    let showTime = false, format = FORMAT;
    if (classid === 'BS000010000100001034') {
        showTime = true;
        format = TIMEFORMAT;
    }
    return (
        <NCDatePicker
            fieldid={fieldid}
            disabled={disabled}
            showTime={showTime}
            format={format}
            value={record[attrcode]}
            onChange={(v) => {
                onValChange({ ...params, val: v });
            }}
        />
    )
}

// 数值 
function drawNCNumber(params) {
    let { page, record, disabled, fieldid, attrcode } = params;
    let tempItem = record.selectCell || record;
    let { inputlength, digit = '0' } = tempItem;
    let { json } = page.state;
    return (
        <NCNumber
            fieldid={fieldid}
            disabled={disabled}
            scale={Number(digit ? digit : '0')}
            value={record[attrcode]}
            maxlength={Number(inputlength) + Number(digit)}
            // placeholder={json['publiccomponents-000004']}/* 国际化处理： 请输入数字*/
            onChange={(val) => {
                onValChange({ ...params, val: val });
            }}
        />
    )
}

//布尔
function drawSelectItem(params) {
    let { page, record, disabled, fieldid, attrcode } = params;
    let { json } = page.state;
    return (
        <SelectItem
            name={record.checktypecode}
            fieldid={fieldid}
            disabled={disabled}
            defaultValue={record[attrcode]}
            items={
                () => {
                    return ([{
                        label: json['publiccomponents-000005'],/* 国际化处理： 是*/
                        value: 'Y'
                    }, {
                        label: json['publiccomponents-000006'],/* 国际化处理： 否*/
                        value: 'N'
                    }, {
                        label: '空',/* 国际化处理： 空 json['publiccomponents-000006']*/
                        value: ''
                    }])
                }
            }
            onChange={(val) => {
                onValChange({ ...params, val: val });
            }}
        />
    )
}

//字符
function drawNCFormControl(params) {
    let { page, record, disabled, fieldid, attrcode, classid } = params;
    let maxlength = record.inputlength || (record.selectCell?record.selectCell.inputlength:"" ) ;
    return (
        <NCFormControl
            fieldid={fieldid}
            disabled={disabled}
            maxlength={maxlength}
            value={record[attrcode]}
            onChange={(val) => {
                let tempVal = onNumberInputChange(val, record, classid);
                onValChange({ ...params, val: tempVal });
            }}
        />
    )
}
//参照onChange事件
function onAssidReferChange(params) {
    let { page, record, val, attrcode, tableDataKey, pkValueType } = params;
    let tableData = page.state[tableDataKey];
    if(tableDataKey === 'tableSourceData'){
        let refpkArr = [], selectCell = [], pk_checkvalue = '';
        val.forEach((item)=>{
            if(pkValueType === 'str'){
                refpkArr.push(item.refpk);
                pk_checkvalue = refpkArr.join(',')
            } else if(pkValueType === 'arr'){
                let cellObj = {};
                cellObj.pk_checkvalue = item.refpk;
                cellObj.checkvaluecode = item.refcode;
                cellObj.checkvaluename = item.refname;
                refpkArr.push(cellObj);
                pk_checkvalue = [...refpkArr];
            }
            selectCell.push(item)
            
        })
        record.selectRange = pk_checkvalue;
        record.selectCells = selectCell;
        page.setState({
            [tableDataKey]: tableData
        });
    } else {
        let newDate = tableData;
        newDate[record.key][attrcode] = val;
        page.setState({
            [tableDataKey]: [...newDate]
        });
    }
}

function onValChange(params) {
    let { page, attrcode, tableDataKey, index, val } = params;
    let tableData = page.state[tableDataKey]
    tableData[index][attrcode] = val;
    page.setState({
        [tableDataKey]: tableData
    })
}

function onNumberInputChange(value, record, classid) {
    let re = new RegExp('');
    if (classid === 'BS000010000100001004') { //整数
        let intLength = record.inputlength || record.selectCell.inputlength;
        re = new RegExp("^(\\d{0," + intLength + "})");
    } else if (classid === 'BS000010000100001031') { //数值小数
        let intLength = record.inputlength || record.selectCell.inputlength;
        let doubleLength = record.digit || record.selectCell.digit;
        re = new RegExp("^(\\d{0," + intLength + "})(\\.\\d{0," + doubleLength + "})?"); //$
    } else {
        return value;
    }
    let result = value && value.length > 0 && re.exec(value);
    return result && result[0] || '';
}

//****************************************************************************************************** */

/**
 * @description: 查询对象
 */
function drawSearchObj(params) {
    let {page, text, record, index, disabled} = params;
    let renderArr = [];
    text.map((item, index) => { 
        let tempVal = item.pk_checktype ? `${item.pk_checktype}_${item.classid}` : '';
        renderArr.push(<NCOption value={tempVal} data={JSON.stringify(item)} name={item.name} key={index > 0 ? index : ''}>{item.name}</NCOption>) //value={JSON.stringify(item)} key={index}
    })
    return (
        <NCSelect
            showClear={false}
            // allowClear
            showSearch={true}
            disabled={disabled}
            fieldid='searchObj'
            value={record.selectCell && record.selectCell.name}
            filterOption={(inputValue,option)=>{
                if(option.children.includes(inputValue)){
                    return true;
                }
            }}
            onChange = {(value, oldvalue, option) => {
                handleSearchObj({page, value, option, record})
            }}
        >
            {
                renderArr
            }
        </NCSelect>
    )
}

function handleSearchObj(params){//查询对象选择具体科目
    let { page, value, option,  record } = params;
    let transValue = JSON.parse(option.data)
    let { tableSourceData, selectRow } = page.state;
    let originData = findByKey(record.key, tableSourceData);
    originData.selectCell = transValue;
    record.selectCells = [];
    record.selectRange = [];
    if(transValue.refpath ){
        originData.type = 'referpath';
        originData.searchRange = transValue.refpath;
    }else if(transValue.datatype === '1'){//字符
        originData.type = 'string';
    } else if(transValue.datatype === '4'){//整数
        originData.type = 'integer';
    } else if(transValue.datatype === '31'){//数值(小数)
        originData.type = 'number';
    } else if(transValue.datatype === '32'){//布尔
        originData.type = 'boolean';
    } else if(transValue.datatype === '33'){//日期
        originData.type = 'date'
    } else if(transValue.datatype === '34'){//日期+时分秒时间
        originData.type = 'dateTime'
    } else if(transValue.attr){
        originData.selectCellAttr = [...transValue.attr];
        originData.type = 'modal'
    } else {
        originData.type = ''
    }
    let newSelectRow = [...selectRow];
    newSelectRow[record.key] = record;
    page.setState({
        tableSourceData,
        selectRow: newSelectRow,
    })
}

//根据key获取表格行数据
function findByKey(key, rows) {
    let rowData = null;
    rows.forEach((item) =>{
        if (item.key == key) {
            rowData = item;
        }
    });
    return rowData;
}

export {
    drawAssidCell,
    drawReferLoader,
    drawOtherAssid,
    drawSearchObj
}

/*v9SsMbU6/en1uSuPJ2mptqF+jolE0EBwO372IvrfdFi2wKSOmX+ORnrDDvO5/aGv*/